#include<termios.h>                                               //头文件
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <string.h>


void serial_init(int fd) //一个初始化串口的函数
{
    struct termios options;
    tcgetattr(fd, &options);
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~CSIZE;
    options.c_cflag &= ~CRTSCTS;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CSTOPB;
    options.c_iflag |= IGNPAR;
    options.c_oflag  = 0;
    options.c_lflag  = 0;
	options.c_cc[VEOL] 	= 1;
	//options.c_oflag |= ONLCR;

    cfsetispeed(&options, B115200); //注意这里是4800
    cfsetospeed(&options, B115200);
    tcsetattr(fd, TCSANOW, &options);
}


int main() //主函数
{
    int fd;
    int buf = 512;
    char BUF[buf]; //定义了一个BUF。。存放串口返回的数据。。要定义的足够大。。基本都是200左右。。有时会到达300+近400
    bzero(BUF,buf); //初始化BUF

    fd = open("/dev/ttyUSB0", O_RDWR);//|O_NOCTTY|O_NDELAY);//打开节点
    if(fd<0) //出错返回
    {
        perror("Can't open!\n");
    }

	char *buf1 = {0};
	buf1 = (char*)malloc(buf);
	memset(buf1,0,buf);
	buf1 = "AT+CGPSPWR=1\r";
	
    serial_init(fd); //初始化串口
	
    int n = write(fd,buf1,100);
	printf("%d\n",n);
	sleep(3);
	int m = read(fd,BUF,100);
	if(m < 0)
	{
		perror("/dev:");
	}
	printf("%s\n",BUF);
	
	sleep(3);
	buf1 = "AT+CGPSRST=1\r"; 
	write(fd,buf1,100);
	sleep(3);
	read(fd,BUF,100);
	printf("%s\n",BUF);
	
	sleep(3);
	buf1 = "AT+CGPSIPR=115200\r"; 
	write(fd,buf1,100);
	sleep(3);
	read(fd,BUF,100);
	printf("%s\n",BUF);
	
	getchar();
	
	sleep(3);
	buf1 = "AT+CGPSPWR=0\r"; 
	write(fd,buf1,100);
	sleep(3);
	read(fd,BUF,100);
	printf("%s\n",buf1);
	
	
	while(1);
    close (fd); //关闭文件描述符

    return 0;
}

/*#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#define BUF_SIZE  16

int main()
{
	char *buf = {0};
	//char buf[BUF_SIZE] = {0};
	int count;
	buf = (char*)malloc(10);
	memset(buf,0,10);

	int fd = open("/dev/ttyUSB0", O_RDWR);
	if (fd == -1 ) {
		perror("open");
		printf("error: can't open file /dev/hahaha\n");
		return -1;
	}
	
	buf = "AT+CGPSPWR=1";
	count = 10;
	int n ;
	n = write(fd,buf,100);
	read(fd,buf,10);
	printf("%s\n",buf);
	printf("%d\n",n);
	sleep(2);
	n = write(fd,"AT+CGPSRST=1",100);
	printf("%d\n",n);
	sleep(2);
	n = write(fd,"AT+CGPSIPR=115200",100);
	printf("%d\n",n);
while(1);
	close(fd);	

	return 0;
}
*/
